<template>
  <el-dialog
    :append-to-body="true"
    :close-on-click-modal="false"
    :visible.sync="dialogVisible"
    title="添加推送用户"
    width="960px"
    @close="$emit('closeUser', selection)"
  >
    <div class="flex">
      <!--      <div class="classify-wrap">-->
      <!--        <el-input v-model="filterText" clearable placeholder="输入关键字进行过滤" size="small"></el-input>-->
      <!--        <el-tree-->
      <!--          ref="tree"-->
      <!--          :data="treeData"-->
      <!--          :default-expand-all="true"-->
      <!--          :expand-on-click-node="false"-->
      <!--          :filter-node-method="filterNode"-->
      <!--          :highlight-current="true"-->
      <!--          :props="{-->
      <!--            label: 'name',-->
      <!--            value: 'id',-->
      <!--            children: 'children',-->
      <!--          }"-->
      <!--          class="mt-3"-->
      <!--          node-key="id"-->
      <!--          @node-click="nodeClick"-->
      <!--        >-->
      <!--        </el-tree>-->
      <!--      </div>-->
      <div class="crud-wrap" style="min-height: 666px">
        <avue-crud
          ref="crud"
          v-model="form"
          :data="tableData"
          :option="tableOption"
          :page.sync="page"
          :search.sync="searchForm"
          :table-loading="tableLoading"
          @on-load="loadListData"
          @search-change="onSearchChange"
          @search-reset="onSearchReset"
          @selection-change="onSelectionChange"
        >
        </avue-crud>
      </div>
      <div class="selected-wrap">
        <div class="selected-wrap-header flex justify-between items-center">
          <span>已选（{{ selection.length }}）</span>
          <el-button type="text" @click="clearSelection">清空</el-button>
        </div>
        <div class="selected-wrap-content mt-3">
          <div v-for="row in selection" :key="row.id" class="selected-item flex justify-between items-center">
            <el-tooltip :content="row.nickName" effect="dark" placement="top">
              <span class="selected-item__label text-ellipsis">
                {{ row.nickName }}
              </span>
            </el-tooltip>
            <el-button icon="el-icon-close" type="text" @click="handleRemove(row)"></el-button>
          </div>
        </div>
      </div>
    </div>
    <div slot="footer">
      <el-button icon="el-icon-check" size="small" type="primary" @click="$emit('closeUser', selection)">
        确 定
      </el-button>
      <el-button icon="el-icon-close" size="small" @click="$emit('closeUser', [])">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { requestUserPage } from '@/api/system/user'
import { requestDepartmentTreeList } from '@/api/system/dept'
import ListMixin from '@/utils/mixins/list-mixin'

const ROOT_NODES = [
  {
    id: 'root',
    name: '全部',
    children: [],
  },
]
export default {
  name: 'UserDialog',
  mixins: [ListMixin],
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    userData: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      currentNodeData: {},
      listApi: requestUserPage,
      tableOption: {
        selection: true,
        reserveSelection: true,
        selectable: this.selectable,
        rowKey: 'id',
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        menu: false,
        searchIcon: false,
        searchSpan: 16,
        refreshBtn: false,
        columnBtn: false,
        column: [
          {
            label: '姓名',
            prop: 'nickName',
            type: 'input',
            align: 'center',
            search: true,
            minWidth: 100,
            overHidden: true,
          },
          {
            label: '工号',
            prop: 'username',
            type: 'input',
            align: 'center',
            minWidth: 100,
            overHidden: true,
          },
          {
            label: '手机号',
            prop: 'phone',
            type: 'input',
            align: 'center',
            minWidth: 100,
            overHidden: true,
          },
          {
            label: '部门',
            prop: 'deptId',
            type: 'tree',
            props: {
              label: 'name',
              value: 'deptId',
            },
            dicUrl: '/api/dept/tree',
            dicMethod: 'post',
            dicQuery: {},
            search: false,
            rules: [{ required: true, message: '请选择所在部门' }],
            addDisabled: false,
            span: 12,
            align: 'left',
            overHidden: true,
          },
        ],
      },
      filterText: '',
      searchForm: {},
      treeData: [],
      tableData: [],
      sourceList: [],
      selection: [],
      classifyId: 2,
    }
  },
  computed: {
    currentNodeKey() {
      if (!this.currentNodeData) {
        return 'root'
      }
      return this.currentNodeData.id
      this.loadListData()
    },
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    },
  },
  created() {
    //this.loadTreeData()
    this.selection = this.userData
  },
  methods: {
    selectable(row) {
      return !this.userData.some((item) => item.id === row.id || Number(item.userId) === row.id)
    },
    getRowKey(row) {
      return row.id
    },
    filterNode(value, data) {
      if (!value) return true
      return data.deptName.indexOf(value) !== -1
    },
    async loadTreeData() {
      console.log('loadTreeData')
      this.treeData = await this.loadDepartmentTree()
      this.$refs.tree && this.$refs.tree.setCurrentKey(this.currentNodeKey)
    },
    async loadDepartmentTree() {
      let ret = ROOT_NODES // 通过一个常量来确保树的根节点不变化，避免一些无法高亮的问题
      try {
        const { success, data } = await requestDepartmentTreeList({})
        if (success) {
          ret[0].children = data
        }
      } catch (error) {
        console.log(error)
      }
      return ret
    },
    nodeClick(data) {
      this.currentNodeData = data
      this.searchForm.deptId = data.id
      this.onSearchChange()
    },
    handleRemove(row) {
      this.$refs.crud.$refs.table.toggleRowSelection(row, false)
    },
    clearSelection() {
      this.$refs.crud.$refs.table.clearSelection()
    },
  },
}
</script>

<style lang="scss" scoped>
.flex {
  display: flex;
  flex-direction: row;
}
.items-center {
  align-items: center;
}
.justify-between {
  justify-content: space-between;
}
.classify-wrap,
.crud-wrap,
.selected-wrap {
  max-height: 60vh;
  overflow-y: auto;
}

.classify-wrap {
  flex: 0;
  padding: 0 5px;
  min-width: 220px;
  overflow: auto;

  .classify-tree {
    display: inline-block;
    min-width: 100%;
  }
}

.crud-wrap {
  flex: 1;
  padding-left: 20px;
  padding-right: 20px;
  border-right: 1px solid #f1f1f1;
  border-left: 1px solid #f1f1f1;
}

.selected-wrap {
  flex: 0;
  padding: 0 10px;
  min-width: 220px;
  overflow-y: auto;

  .selected-item {
    height: 30px;

    .selected-item__label {
      max-width: 80%;
    }
  }
}
</style>
